<template>
    <div style="margin-left: 15px; margin-right: 15px; height: 100%">
        <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents" @checkbox-change="handleSelectionChange" :params="searchInfo" style="height: 100%">
            <template #toolbar_tools>
                <vxe-input placeholder="搜索"></vxe-input>
            </template>
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5" v-hasPermi="['system:role:add']">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5" v-hasPermi="['system:role:edit']">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate(null)">修改</el-button>
                    </el-col>
                    <el-col :span="1.5" v-hasPermi="['system:role:remove']">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(null)">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <vxe-switch v-model="row['status']" size="medium" :open-value="0" :close-value="1" :disabled="!proxy.$auth.hasPermi('system:role:edit')" @change="handleStatusChange(row)"></vxe-switch>
            </template>
            <template #action="{ row }">
                <el-tooltip content="修改" placement="top">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:role:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                    <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:role:remove']"></el-button>
                </el-tooltip>
            </template>
        </vxe-grid>
        <el-dialog v-model="visible" draggable title="分配数据权限" destroyOnClose width="500px" append-to-body>
            <el-form :model="form" label-width="80px">
                <el-form-item label="授权值">
                    <el-input v-model="form.powerValue" type="textarea" placeholder="请输入授权值"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
                    <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
                    <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
                    <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id" :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候" :props="{ label: 'label', children: 'children' }"></el-tree>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
    import { defineComponent, ref, unref, reactive, getCurrentInstance, toRefs, nextTick } from "vue";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners, VxeGridEvents, VxeGridDefines } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import useBaseApi from "@/api/base/index";
    import { useRoute } from "vue-router";
    import { changeRoleStatus, updatePowerMenuIds, addPowerMenuIds } from "@/api/system/power";
    import { roleMenuTree } from "@/api/system/menu";
    import { VXETable } from "../../../../packages/all";
    import { removeObjectNull } from "@/utils";
    export default defineComponent({
        components: {},
        setup() {
            const router = useRoute();
            const { proxy } = getCurrentInstance() as any;
            const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
            const { callModify, callPageList, callGetOne, callRemoves, callSave } = useBaseApi("/system/power");
            const xGrid = ref({} as VxeGridInstance);
            const visible = ref<Boolean>(false);
            const single = ref(true);
            const multiple = ref(true);
            const menuExpand = ref(false);
            const menuNodeAll = ref(false);
            const menuOptions = ref([]);
            const menuRef = ref<any>();
            const roleId = ref(router.params && router.params.roleId);
            const data: any = reactive({
                form: {},
            });
            const { form } = toRefs(data);
            function getTableAction() {
                const tableAction = unref(xGrid);
                if (!tableAction) {
                    throw new Error("tableAction is null");
                }
                return tableAction;
            }
            const searchInfo = reactive<any>({
                bidId: 0,
            });

            const gridOptions = reactive<VxeGridProps>({
                border: true,
                resizable: true,
                showHeaderOverflow: true,
                showOverflow: true,
                highlightHoverRow: true,
                keepSource: true,
                id: "21",
                height: "auto",
                rowId: "rmpId",
                customConfig: {
                    storage: true,
                },
                sortConfig: {
                    trigger: "cell",
                    remote: true,
                },
                filterConfig: {
                    remote: true,
                },
                pagerConfig: {
                    pageSize: 10,
                    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
                    perfect: true,
                },
                formConfig: {
                    titleWidth: 100,
                    titleAlign: "right",
                    items: [
                        {
                            field: "menuId",
                            span: 5,
                            itemRender: { name: "$input", props: { placeholder: "请输入菜单ID" } },
                            title: "菜单ID",
                        },
                        {
                            field: "menuName",
                            span: 5,
                            itemRender: { name: "$input", props: { placeholder: "请输入菜单名称" } },
                            title: "菜单名称",
                        },
                        {
                            field: "status",
                            title: "状态",
                            span: 5,
                            itemRender: {
                                name: "$select",
                                options: sys_normal_disable,
                            },
                        },
                        {
                            field: "createTime",
                            title: "创建时间",
                            span: 5,
                            itemRender: {
                                name: "ElDatePicker",
                                props: {
                                    valueFormat: "YYYY-MM-DD",
                                    type: "daterange",
                                    rangeSeparator: "-",
                                    startPlaceholder: "开始日期",
                                    endPlaceholder: "结束日期",
                                },
                            },
                        },
                        {
                            itemRender: {
                                name: "$buttons",
                                children: [
                                    {
                                        props: {
                                            type: "submit",
                                            content: "查询",
                                            status: "primary",
                                        },
                                    },
                                    {
                                        props: {
                                            type: "reset",
                                            content: "重置",
                                        },
                                    },
                                ],
                            },
                        },
                    ],
                },
                toolbarConfig: {
                    refresh: true,
                    export: false,
                    print: false,
                    zoom: true,
                    custom: true,
                    slots: {
                        tools: "toolbar_tools",
                        buttons: "toolbar_buttons",
                    },
                },
                proxyConfig: {
                    paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
                    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
                    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
                    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
                    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
                    // 对应响应结果 { result: [], page: { total: 100 } }
                    props: {
                        result: "rows", // 配置响应结果列表字段
                        total: "total", // 配置响应结果总页数字段
                    },
                    ajax: {
                        // 接收 Promise
                        query: ({ page, sorts, filters, form, params }: any) => {
                            // 处理时间范围查询
                            const createTime = proxy.addDateRange({}, form.createTime, "createTime");
                            const queryParams: any = Object.assign({}, form, createTime, page, params);
                            // 处理排序条件
                            const orderByColumn = <Array<String>>[];
                            const isAsc = <Array<Boolean>>[];
                            sorts.forEach((m: any) => {
                                orderByColumn.push(m.field);
                                isAsc.push(m.order);
                            });
                            queryParams.orderByColumn = orderByColumn.join(",");
                            queryParams.isAsc = isAsc.join(",");
                            // 处理筛选条件
                            filters.forEach(({ property, values }: any) => {
                                queryParams[property] = values.join(",");
                            });
                            return callPageList({
                                ...removeObjectNull(queryParams),
                                roleId: roleId.value,
                            }).then((response) => {
                                return response;
                            });
                        },
                    },
                },
                columns: [
                    { type: "checkbox", width: 60, fixed: "left" },
                    {
                        field: "rmpId",
                        title: "授权ID",
                    },
                    {
                        field: "roleId",
                        title: "角色ID",
                    },
                    {
                        field: "roleName",
                        title: "角色名称",
                    },
                    {
                        field: "menuId",
                        title: "菜单ID",
                    },
                    {
                        field: "menuName",
                        title: "菜单名称",
                    },
                    {
                        field: "powerValue",
                        title: "授权值",
                    },
                    {
                        field: "sort",
                        title: "排序",
                    },
                    {
                        field: "status",
                        title: "状态",
                        filters: sys_normal_disable,
                        slots: {
                            default: "slotStatus",
                        },
                    },
                    {
                        field: "createTime",
                        title: "创建时间",
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        title: "操作",
                        width: 170,
                        align: "center",
                        fixed: "right",
                        slots: { default: "action" },
                    },
                ],
                checkboxConfig: {
                    labelField: "id",
                    reserve: true,
                    highlight: true,
                    range: true,
                    trigger: "row",
                },
            });

            /** 多选框选中数据 */
            function handleSelectionChange(data: any) {
                single.value = data.records.length != 1;
                multiple.value = !data.records.length;
            }

            /** 添加授权 */
            async function handleAdd() {
                menuOptions.value = await getRoleMenuTreeselect(roleId.value);
                console.log("添加", menuOptions.value);
                visible.value = true;
                form.value = {
                    rmpId: null,
                    roleId: roleId,
                    menuId: null,
                    powerValue: "",
                    sort: 0,
                    status: "0",
                    menuCheckStrictly: true,
                };
                // nextTick(() => {
                //     menuRef.value.setChecked(100, true);
                //     menuRef.value.setCurrentKey(101, true);
                // });
            }
            /** 修改授权 */
            async function handleUpdate(row: any) {
                console.log("修改", row);
                const rmpId = row?.rmpId || getTableAction().getCheckboxRecords()[0]?.rmpId;
                const editRoleId = row?.roleId || getTableAction().getCheckboxRecords()[0]?.roleId;
                menuOptions.value = await getRoleMenuTreeselect(editRoleId);
                callGetOne(rmpId).then((response: any) => {
                    form.value = {
                        ...response.data,
                        sort: Number(response.data.sort),
                        status: String(response.data.status),
                    };
                    visible.value = true;
                    console.log("menuRef.value", menuRef.value, form.value);
                    nextTick(() => {
                        menuRef.value.setChecked(form.value.menuId, true);
                        menuRef.value.setCurrentKey(form.value.menuId, true);
                    });
                });
            }

            /** 根据角色ID查询菜单树结构 */
            function getRoleMenuTreeselect(roleId: any) {
                return roleMenuTree(roleId).then((response: any) => {
                    return response.data;
                });
            }
            /** 树权限（展开/折叠）*/
            function handleCheckedTreeExpand(value: any) {
                let treeList: any = menuOptions.value;
                for (let i = 0; i < treeList.length; i++) {
                    menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
            /** 树权限（全选/全不选） */
            function handleCheckedTreeNodeAll(value: any) {
                menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
            }
            /** 树权限（父子联动） */
            function handleCheckedTreeConnect(value: any) {
                form.value.menuCheckStrictly = value ? true : false;
            }
            /** 所有菜单节点数据 */
            function getMenuAllCheckedKeys() {
                // 目前被选中的菜单节点
                let checkedKeys = menuRef.value.getCheckedKeys();
                // 半选中的菜单节点
                let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
                checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
                return checkedKeys;
            }

            /** 删除按钮操作 */
            async function handleDelete(row: any) {
                const list = await getTableAction().getCheckboxRecords();
                const rmpIds = row.rmpId || list.map((item: any) => item.rmpId);
                proxy.$modal
                    .confirm('是否确认删除授权编号为"' + rmpIds + '"的数据项?')
                    .then(function () {
                        return callRemoves(rmpIds);
                    })
                    .then(() => {
                        xGrid.value.commitProxy("reload");
                        proxy.$modal.msgSuccess("删除成功");
                    })
                    .catch(() => {});
            }

            /** 角色状态修改 */
            function handleStatusChange(row: any) {
                let text = row.status === "0" ? "启用" : "停用";
                proxy.$modal
                    .confirm('确认要"' + text + '" "' + row.menuName + '"授权吗?')
                    .then(function () {
                        return changeRoleStatus(row.rmpId, row.status);
                    })
                    .then(() => {
                        proxy.$modal.msgSuccess(text + "成功");
                        getTableAction().commitProxy("reload");
                    })
                    .catch(function () {
                        row.status = row.status === "0" ? "1" : "0";
                    });
            }
            /** 提交按钮 */
            function submitForm() {
                if (form.value.rmpId != undefined) {
                    form.value.menuIds = getMenuAllCheckedKeys();
                    updatePowerMenuIds(form.value).then((response) => {
                        proxy.$modal.msgSuccess("修改成功");
                        visible.value = false;
                    });
                } else {
                    form.value.menuIds = getMenuAllCheckedKeys();
                    addPowerMenuIds(form.value).then((response) => {
                        proxy.$modal.msgSuccess("添加成功");
                        visible.value = false;
                    });
                }
            }
            // 取消
            const cancel = () => {
                visible.value = false;
            };
            return {
                xGrid,
                gridOptions,
                searchInfo,
                handleAdd,
                handleUpdate,
                single,
                multiple,
                handleSelectionChange,
                handleDelete,
                handleStatusChange,
                proxy,
                visible,
                submitForm,
                form,
                cancel,
                menuExpand,
                menuNodeAll,
                menuOptions,
                menuRef,
                handleCheckedTreeExpand,
                handleCheckedTreeNodeAll,
                handleCheckedTreeConnect,
                sys_normal_disable,
            };
        },
    });
</script>
